import axios from 'axios';
import * as XLSX from 'xlsx';
import UserService from './UserService.js';
import { ElMessage } from 'element-plus';
import router from '../router';

// 创建axios实例
const api = axios.create({
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  validateStatus: status => status >= 200 && status < 300
});

// 请求拦截器，自动加token
api.interceptors.request.use(config => {
  const token = localStorage.getItem('token') || (UserService.getCurrentUser && UserService.getCurrentUser().token) || '';
  if (token) {
    config.headers.token = token;
  }
  return config;
});

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    console.log("jd");
    console.log(response);
    return response
  },
  (error) => {
    //如果响应的状态码为401, 则路由到登录页面
    if (error.response.status === 401) {
      ElMessage.error('登录失效, 请重新登录')
      router.push('/login')
    } else {
      ElMessage.success('接口访问异常')
    }
    return Promise.reject(error)
  }
);

class CourseService {
  // 获取课程列表（分页）
  async getCourseListWithPage(params = {}) {
    try {
      // 添加当前用户ID参数
      const queryParams = { ...params };
      queryParams.currentUserId = UserService.getCurrentUserId();

      console.log('CourseService - 发送分页请求参数:', queryParams);

      const response = await api.get('/api/course/list-page', { params: queryParams });
      console.log('CourseService - 获取分页课程列表响应:', response.data);
      return response.data;
    } catch (error) {
      console.error('获取分页课程列表失败:', error);
      throw error;
    }
  }

  // 搜索课程
  async searchCourse(params) {
    try {
      // 添加当前用户ID参数
      const queryParams = { ...params };
      queryParams.currentUserId = UserService.getCurrentUserId();

      const response = await api.get('/api/course/search', { params: queryParams });
      return response.data;
    } catch (error) {
      console.error('搜索课程失败:', error);
      throw error;
    }
  }

  // 获取课程详情
  async getCourseDetail(courseId) {
    try {
      const response = await api.get('/api/course/detail', {
        params: { courseId }
      });
      return response.data;
    } catch (error) {
      console.error('获取课程详情失败:', error);
      throw error;
    }
  }

  // 新增课程
  async addCourse(course) {
    try {
      // 添加当前用户ID参数
      const currentUserId = UserService.getCurrentUserId();
      console.log('CourseService - 新增课程，当前用户ID:', currentUserId);

      const response = await api.post('/api/course/add', course, {
        params: { currentUserId }
      });
      return response.data;
    } catch (error) {
      console.error('新增课程失败:', error);
      throw error;
    }
  }

  // 更新课程
  async updateCourse(course) {
    try {
      const isAdmin = UserService.isAdmin();
      const response = await api.put(`/api/course/update/${isAdmin}`, course)
      return response.data;
    } catch (error) {
      console.error('更新课程失败:', error);
      throw error;
    }
  }

  // 删除课程
  async deleteCourse(courseId) {
    try {
      const response = await api.delete('/api/course/delete', {
        params: { courseId }
      });
      return response.data;
    } catch (error) {
      console.error('删除课程失败:', error);
      throw error;
    }
  }

  // 审核课程
  async reviewCourse(courseId, status) {
    try {
      const response = await api.post('/api/course/review', null, {
        params: { courseId, status }
      });
      console.log('CourseService - 审核课程响应:', response.data);
      return response.data;
    } catch (error) {
      console.error('审核课程失败:', error);
      throw error;
    }
  }

  // 批量删除课程 - 暂时使用循环删除单个课程
  async batchDeleteCourse(courseIds) {
    try {
      const results = [];
      for (const courseId of courseIds) {
        const response = await this.deleteCourse(courseId);
        results.push(response);
      }

      // 检查是否所有删除都成功
      const successCount = results.filter(r => r.code === 200).length;
      if (successCount === courseIds.length) {
        return { code: 200, message: `成功删除 ${successCount} 门课程` };
      } else {
        return { code: 500, message: `部分删除失败，成功删除 ${successCount} 门课程` };
      }
    } catch (error) {
      console.error('批量删除课程失败:', error);
      throw error;
    }
  }

  // 导出Excel - 使用xlsx库
  async exportExcel(courseList, params = {}) {
    try {
      // 准备导出数据
      const exportData = courseList.map(course => ({
        '课程ID': course.courseId,
        '课程名称': course.courseName,
        '课程简介': course.courseIntro,
        '课程封面': course.courseCover || '无封面',
        '课程排序': course.courseSort,
        '课程作者': course.courseAuthor,
        '创建人ID': course.createPersonId,
        '审核状态': this.getReviewStatusText(course.courseStatus)
      }));

      // 创建工作簿
      const workbook = XLSX.utils.book_new();

      // 创建工作表
      const worksheet = XLSX.utils.json_to_sheet(exportData);

      // 设置列宽
      const colWidths = [
        { wch: 10 }, // 课程ID
        { wch: 30 }, // 课程名称
        { wch: 40 }, // 课程简介
        { wch: 20 }, // 课程封面
        { wch: 12 }, // 课程排序
        { wch: 15 }, // 课程作者
        { wch: 12 }, // 创建人ID
        { wch: 12 }  // 审核状态
      ];
      worksheet['!cols'] = colWidths;

      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, '课程列表');

      // 生成文件名
      const fileName = `课程列表_${new Date().toISOString().split('T')[0]}.xlsx`;

      // 导出文件
      XLSX.writeFile(workbook, fileName);

      return { success: true, message: '导出成功' };
    } catch (error) {
      console.error('导出Excel失败:', error);
      throw error;
    }
  }

  // 获取审核状态文本
  getReviewStatusText(status) {
    switch (status) {
      case 0:
        return '未审核';
      case 1:
        return '已审核';
      case 2:
        return '已拒绝';
      default:
        return '未知状态';
    }
  }

  // 获取审核状态类型（用于标签颜色）
  getReviewStatusType(status) {
    switch (status) {
      case 0:
        return 'warning';
      case 1:
        return 'success';
      case 2:
        return 'danger';
      default:
        return 'info';
    }
  }
}

export default new CourseService(); 